package com.prototype.web.controller.admin;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Date;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.prototype.constants.AdminStatus;
import com.prototype.po.Admin;
import com.prototype.service.AdminSerice;
import com.prototype.web.controller.BaseController;
import com.prototype.web.model.AdminLoginModel;
import com.prototype.web.vo.AdminVO;

/**
 * 登录controller
 * 
 * @author eg366
 * 
 */
@Controller
@RequestMapping("/admin")
public class LoginController extends BaseController {

	@Autowired
	private AdminSerice adminService;

	/**
	 * 访问登录页
	 */
	@RequestMapping(value = { "/index.htm", "/login.htm" })
	public String index(ModelMap model) {
		model.addAttribute("loginModel", new AdminLoginModel());
		return "admin.login.def";
	}

	/**
	 * 提交执行登录操作
	 * 
	 * @return
	 */
	@RequestMapping("/doLogin.htm")
	public String doLogin(
			@Valid @ModelAttribute(value = "loginModel") AdminLoginModel loginModel,
			BindingResult result, ModelMap model) {
		if (result.hasErrors()) {
			// result.getFieldError().getDefaultMessage();
			return "admin.login.def";
		}
		/* 校验验证码 */
		String authCode = getSessionStrByParam("authCode");
		if (!loginModel.getAuthCode().equals(authCode)) {
			model.addAttribute("errMsg", "验证码错误");
			return "admin.login.def";
		}
		Admin admin = adminService.getByNamePwd(loginModel.getLoginName(),
				loginModel.getPassword());
		if (admin == null) {
			model.addAttribute("errMsg", "用户名或密码错误");
			return "admin.login.def";
		}
		if (!AdminStatus.NORMAL.code.equals(admin.getStatus())) {
			model.addAttribute("errMsg", "操作员状态异常");
			return "admin.login.def";
		}
		/* 更新最后登录时间 */
		admin.setLastLoginDate(new Date());
		this.adminService.update(admin);
		
		saveAdminOperator(new AdminVO(admin.getUserName(), admin.getLoginName()));
		return "admin.welcome.def";
	}

	/**
	 * 验证码
	 * 
	 * @throws IOException
	 */
	@RequestMapping(value = "/authCode.htm")
	public void authCode(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		// 取得一个1000-9999的随机数
		HttpSession session = request.getSession();// request.getSession(false)当参数为false时，有可能不创建session
		response.setContentType("image/gif");
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);

		// 可选字体
		String[] FontFamily = { "Verdana", "Times New Roman", "宋体", "黑体",
				"Arial Unicode MS", "Lucida Sans" };
		int width = 70;
		int height = 20;
		if (request.getParameter("width") != null
				&& !request.getParameter("width").equals(""))
			width = Integer.parseInt(request.getParameter("width"));
		if (request.getParameter("height") != null
				&& !request.getParameter("height").equals(""))
			height = Integer.parseInt(request.getParameter("height"));

		ServletOutputStream out = response.getOutputStream();
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB); // 设置图片大小的
		Graphics gra = image.getGraphics();
		Random random = new Random();
		gra.setColor(new Color(0, 198, 233)); // 设置背景色
		gra.fillRect(0, 0, width, height);
		gra.setColor(Color.black); // 设置字体色
		gra.setFont(new Font(FontFamily[new Random().nextInt(6)], Font.BOLD, 16));

		// 随机产生155条干扰线，使图象中的认证码不易被其它程序探测到
		gra.setColor(new Color(181, 69, 197));
		for (int i = 0; i < 80; i++) {
			int x = random.nextInt(width);
			int y = random.nextInt(height);
			int xl = random.nextInt(12);
			int yl = random.nextInt(12);
			gra.drawLine(x, y, x + xl, y + yl);
		}

		// 取随机产生的认证码(4位数字)
		String sRand = "";
		for (int i = 0; i < 6; i++) {
			String rand = String.valueOf(random.nextInt(10));
			sRand += rand;
			// 将认证码显示到图象中
			gra.setColor(new Color(255, 255, 255));// 调用函数出来的颜色相同，可能是因为种子太接近，所以只能直接生成
			gra.drawString(rand, 11 * i + 3, 16);
		}
		String atrName = request.getParameter("atrName");
		if (StringUtils.isNotBlank(atrName)) {
			session.setAttribute(atrName, sRand);
		} else {
			session.setAttribute("authCode", sRand);
		}

		ImageIO.write(image, "JPEG", out);
	}
}
